<template>
  <view class="warehouse-container">
    <!-- A. 页面头部 -->
    <view class="page-header">
      <text class="page-title">标签打印</text>
    </view>

    <!-- B. 标签打印表单 -->
    <view class="info-section">
      <view class="search-form">
        <view class="section-header">
          <text class="section-title">标签信息</text>
        </view>
        <!-- 物料明细码开关 -->
        <view class="input-switch-container">
          <text class="switch-label"
            >物料明细码{{ materialDetailEnabled ? "开启" : "关闭" }}</text
          >
          <view
            class="custom-switch-wrapper"
            @click="handleMaterialDetailSwitchChange"
          >
            <view
              class="custom-switch"
              :class="{ 'custom-switch-active': materialDetailEnabled }"
            >
              <view
                class="custom-switch-handle"
                :class="{
                  'custom-switch-handle-active': materialDetailEnabled,
                }"
              ></view>
            </view>
          </view>
        </view>
        <view class="info-form">
          <view class="form-item">
            <text class="form-label">创建日期</text>
            <text class="warehouse-display">{{ formData.currentDate }}</text>
          </view>
          <view class="form-item">
            <text class="form-label">物料名称</text>
            <view class="material-combo-selector">
              <input
                class="form-input"
                type="text"
                v-model="materialSearchText"
                placeholder="请输入物料名称进行搜索"
                @input="handleMaterialSearch"
                @focus="showMaterialDropdown = true"
              />
              <text class="input-arrow" @click="toggleMaterialDropdown">▼</text>
              <!-- 物料名称下拉选择 -->
              <view v-if="showMaterialDropdown" class="material-dropdown">
                <view
                  v-for="item in filteredMaterialOptions"
                  :key="item.materialCode"
                  class="material-option"
                  @click="selectMaterial(item)"
                >
                  <view class="material-option-name">{{
                    item.materialName
                  }}</view>
                  <view class="material-option-code">{{
                    item.materialCode
                  }}</view>
                </view>
                <view
                  v-if="filteredMaterialOptions.length === 0"
                  class="no-results"
                >
                  暂无匹配的物料数据
                </view>
              </view>
            </view>
          </view>
          <view class="form-item">
            <text class="form-label">物料编码</text>
            <input
              class="form-input"
              type="text"
              v-model="printForm.materialCode"
              placeholder="物料编码"
              :disabled="true"
            />
          </view>
          <view class="form-item">
            <text class="form-label">备注一</text>
            <input
              class="form-input"
              type="text"
              v-model="printForm.remark1"
              placeholder="请输入备注一"
            />
          </view>
          <view class="form-item">
            <text class="form-label">备注二</text>
            <input
              class="form-input"
              type="text"
              v-model="printForm.remark2"
              placeholder="请输入备注二"
            />
          </view>
        </view>
      </view>
    </view>
    <!-- C. 打印操作区 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">打印操作</text>
      </view>
      <view class="print-actions">
        <button class="btn-submit" @click="handlePrint">
          <text class="btn-text">打印标签</text>
        </button>
        <button class="print-btn secondary" @click="handleReset">
          <text class="btn-text">重置表单</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { getCurrentDate } from "@/pages/smart/utils/date-helper.js";
import { MaterialApi } from "@/api/md/material/index.js";
import { MaterialDetailApi } from "@/api/md/materialdetail/index.js";
import { pdaScanApi } from "@/pages/smart/pdaScan.js";

export default {
  name: "PdaPrint",
  // 混入PDA扫码功能
  mixins: [pdaScanApi],
  data() {
    return {
      // 表单数据
      formData: {
        currentDate: "", // 当前日期
      },
      // 打印表单
      printForm: {
        materialCode: "", // 物料编码
        materialName: "", // 物料名称
        remark1: "", // 备注一
        remark2: "", // 备注二
      },
      // 物料编码下拉选项
      materialCodeOptions: [],
      // 搜索文本
      materialSearchText: "",
      // 是否显示物料下拉框
      showMaterialDropdown: false,
      // 搜索防抖定时器
      searchTimer: null,
      // 点击外部事件处理器
      clickOutsideHandler: null,
      // 物料明细码开关状态
      materialDetailEnabled: false,
    };
  },
  mounted() {
    // 初始化当前日期
    this.formData.currentDate = getCurrentDate();

    // 初始化物料明细码开关状态
    //this.initMaterialDetailSwitch();

    // 加载物料数据（根据开关状态决定加载哪种数据）
    this.loadMaterialData();

    // 添加点击外部关闭下拉框的事件监听
    this.addClickOutsideListener();

    // 初始化PDA扫码模块（来自mixin）
    this.initScanModule();
  },
  computed: {
    /**
     * 物料选项（直接返回API查询结果）
     */
    filteredMaterialOptions() {
      console.log("计算属性 - 物料选项总数:", this.materialCodeOptions.length);
      return this.materialCodeOptions;
    },
  },

  methods: {
    /**
     * 初始化物料明细码开关状态
     */
    initMaterialDetailSwitch() {
      // 从本地存储读取物料明细码开关状态
      const saved = uni.getStorageSync("materialDetailEnabled");
      if (saved !== null && saved !== undefined) {
        this.materialDetailEnabled = saved;
      }
    },

    /**
     * 物料明细码开关切换处理
     */
    handleMaterialDetailSwitchChange() {
      this.materialDetailEnabled = !this.materialDetailEnabled;

      // 保存到本地存储
      uni.setStorageSync("materialDetailEnabled", this.materialDetailEnabled);

      // 重置表单数据
      this.handleReset();

      // 重新加载对应的数据
      this.loadMaterialData();

      // 显示切换提示
      uni.showToast({
        title: `物料明细码已${this.materialDetailEnabled ? "开启" : "关闭"}`,
        icon: "success",
        duration: 1500,
      });
    },

    /**
     * 加载物料数据（根据开关状态决定加载主数据还是明细数据）
     */
    async loadMaterialData() {
      if (this.materialDetailEnabled) {
        await this.loadMaterialDetailData();
      } else {
        await this.loadMaterialMasterData();
      }
    },

    /**
     * 加载物料主数据
     */
    async loadMaterialMasterData() {
      try {
        const params = {
          pageNum: 1,
          pageSize: 100, // 获取前100条物料数据
        };

        console.log("加载物料主数据参数:", params);
        const response = await MaterialApi.getMaterialPage(params);

        console.log("物料主数据加载结果:", response);
        if (response.code === 0 && response.data && response.data.list) {
          this.materialCodeOptions = response.data.list.map((item) => ({
            materialCode: item.materialCode,
            materialName: item.materialName,
            spec: item.spec,
            categoryName: item.categoryName,
          }));
          console.log("物料选项已加载，数量:", this.materialCodeOptions.length);
          console.log("物料数据示例:", this.materialCodeOptions.slice(0, 3));
        } else {
          this.materialCodeOptions = [];
          console.log("未获取到物料数据，响应:", response);
        }
      } catch (error) {
        console.error("加载物料主数据失败:", error);
        this.materialCodeOptions = [];
        uni.showToast({
          title: "加载物料数据失败",
          icon: "none",
        });
      }
    },

    /**
     * 加载物料明细数据
     */
    async loadMaterialDetailData() {
      try {
        const params = {
          pageNum: 1,
          pageSize: 100, // 获取前100条物料明细数据
        };

        console.log("加载物料明细数据参数:", params);
        const response = await MaterialDetailApi.getMaterialDetailPage(params);

        console.log("物料明细数据加载结果:", response);
        if (response.code === 0 && response.data && response.data.list) {
          this.materialCodeOptions = response.data.list.map((item) => ({
            materialCode: item.materialDetailCode, // 使用物料明细编码
            materialName: item.materialDetailName, // 使用物料明细名称
            spec: item.spec,
            categoryName: item.categoryName,
            // 保存原始物料编码和名称，用于打印
            originalMaterialCode: item.materialCode,
            originalMaterialName: item.materialName,
          }));
          console.log(
            "物料明细选项已加载，数量:",
            this.materialCodeOptions.length
          );
          console.log(
            "物料明细数据示例:",
            this.materialCodeOptions.slice(0, 3)
          );
        } else {
          this.materialCodeOptions = [];
          console.log("未获取到物料明细数据，响应:", response);
        }
      } catch (error) {
        console.error("加载物料明细数据失败:", error);
        this.materialCodeOptions = [];
        uni.showToast({
          title: "加载物料明细数据失败",
          icon: "none",
        });
      }
    },

    /**
     * 物料搜索处理（调用API进行模糊查询）
     */
    handleMaterialSearch() {
      // 清除之前的定时器
      clearTimeout(this.searchTimer);

      // 设置防抖，300ms后执行搜索
      this.searchTimer = setTimeout(() => {
        console.log("物料搜索文本:", this.materialSearchText);

        // 立即显示下拉框
        this.showMaterialDropdown = true;

        // 如果搜索文本为空，加载基础数据
        if (!this.materialSearchText.trim()) {
          this.loadMaterialData();
          return;
        }

        // 调用API进行模糊查询
        this.searchMaterialByName(this.materialSearchText.trim());
      }, 300);
    },

    /**
     * 根据物料名称模糊查询（根据开关状态决定查询主数据还是明细数据）
     */
    async searchMaterialByName(searchText) {
      if (this.materialDetailEnabled) {
        await this.searchMaterialDetailByName(searchText);
      } else {
        await this.searchMaterialMasterByName(searchText);
      }
    },

    /**
     * 根据物料名称模糊查询物料主数据
     */
    async searchMaterialMasterByName(searchText) {
      try {
        const params = {
          materialName: searchText, // 使用materialName参数进行模糊查询
          pageNum: 1,
          pageSize: 50, // 获取更多匹配结果
        };

        console.log("模糊查询物料参数:", params);
        const response = await MaterialApi.getMaterialPage(params);

        console.log("模糊查询结果:", response);
        if (response.code === 0 && response.data && response.data.list) {
          this.materialCodeOptions = response.data.list.map((item) => ({
            materialCode: item.materialCode,
            materialName: item.materialName,
            spec: item.spec,
            categoryName: item.categoryName,
          }));
          console.log("模糊查询到物料数量:", this.materialCodeOptions.length);
        } else {
          this.materialCodeOptions = [];
          console.log("未查询到匹配的物料数据");
        }
      } catch (error) {
        console.error("模糊查询物料失败:", error);
        this.materialCodeOptions = [];
        uni.showToast({
          title: "查询物料失败",
          icon: "none",
        });
      }
    },

    /**
     * 切换物料下拉框显示
     */
    toggleMaterialDropdown() {
      this.showMaterialDropdown = !this.showMaterialDropdown;
      if (this.showMaterialDropdown && this.materialCodeOptions.length === 0) {
        // 如果下拉框要显示但没有数据，重新加载
        this.loadMaterialData();
      }
    },

    /**
     * 添加点击外部关闭下拉框的监听
     */
    addClickOutsideListener() {
      this.clickOutsideHandler = (event) => {
        const materialSelector = this.$el.querySelector(
          ".material-combo-selector"
        );
        if (materialSelector && !materialSelector.contains(event.target)) {
          this.showMaterialDropdown = false;
        }
      };
      document.addEventListener("click", this.clickOutsideHandler);
    },

    /**
     * 移除点击外部事件监听
     */
    removeClickOutsideListener() {
      if (this.clickOutsideHandler) {
        document.removeEventListener("click", this.clickOutsideHandler);
        this.clickOutsideHandler = null;
      }
    },

    /**
     * 根据物料名称模糊查询物料明细数据
     */
    async searchMaterialDetailByName(searchText) {
      try {
        const params = {
          materialDetailName: searchText, // 使用物料明细名称参数进行模糊查询
          pageNum: 1,
          pageSize: 50, // 获取更多匹配结果
        };

        console.log("模糊查询物料明细参数:", params);
        const response = await MaterialDetailApi.getMaterialDetailPage(params);

        console.log("模糊查询物料明细结果:", response);
        if (response.code === 0 && response.data && response.data.list) {
          this.materialCodeOptions = response.data.list.map((item) => ({
            materialCode: item.materialDetailCode, // 使用物料明细编码
            materialName: item.materialDetailName, // 使用物料明细名称
            spec: item.spec,
            categoryName: item.categoryName,
            // 保存原始物料编码和名称，用于打印
            originalMaterialCode: item.materialCode,
            originalMaterialName: item.materialName,
          }));
          console.log(
            "模糊查询到物料明细数量:",
            this.materialCodeOptions.length
          );
        } else {
          this.materialCodeOptions = [];
          console.log("未查询到匹配的物料明细数据");
        }
      } catch (error) {
        console.error("模糊查询物料明细失败:", error);
        this.materialCodeOptions = [];
        uni.showToast({
          title: "查询物料明细失败",
          icon: "none",
        });
      }
    },

    /**
     * 选择物料（选择后将物料编码赋值，并将spec赋值到备注一）
     */
    selectMaterial(item) {
      console.log("选择物料:", item);

      if (this.materialDetailEnabled) {
        // 物料明细码模式：使用明细编码和名称
        this.printForm.materialCode = item.materialCode; // materialDetailCode
        this.printForm.materialName = item.materialName; // materialDetailName
        // 保存原始物料编码和名称到备注中
        this.printForm.remark1 = item.originalMaterialCode || "";
        this.printForm.remark2 = item.originalMaterialName || "";
      } else {
        // 物料主数据模式：使用主数据编码和名称
        this.printForm.materialCode = item.materialCode;
        this.printForm.materialName = item.materialName;
        // 将物料的spec赋值到备注一字段
        this.printForm.remark1 = item.spec || "";
        this.printForm.remark2 = "";
      }

      this.materialSearchText = item.materialName;
      this.showMaterialDropdown = false;

      // 显示选择成功的提示
      uni.showToast({
        title: `已选择: ${item.materialName}`,
        icon: "success",
        duration: 1500,
      });
    },

    /**
     * 验证打印表单
     */
    validatePrintForm() {
      if (!this.printForm.materialCode.trim()) {
        uni.showToast({
          title: "请选择物料名称",
          icon: "none",
        });
        return false;
      }

      if (!this.printForm.materialName.trim()) {
        uni.showToast({
          title: "请选择有效的物料名称",
          icon: "none",
        });
        return false;
      }

      return true;
    },

    /**
     * 处理打印
     */
    async handlePrint() {
      // 表单验证
      if (!this.validatePrintForm()) {
        return;
      }

      try {
        console.log("打印参数:", {
          materialCode: this.printForm.materialCode,
          materialName: this.printForm.materialName,
          remark1: this.printForm.remark1,
          remark2: this.printForm.remark2,
        });

        const printResult = this.pdaPrint(
          this.printForm.materialCode,
          this.printForm.materialName,
          this.printForm.remark1,
          this.printForm.remark2
        );

        if (printResult) {
          uni.showToast({
            title: "打印成功",
            icon: "success",
          });
        } else {
          uni.showToast({
            title: "打印失败，请检查设备",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("打印失败:", error);
        uni.showToast({
          title: "打印失败，请重试",
          icon: "none",
        });
      }
    },
    /**
     * 重置表单
     */
    handleReset() {
      this.printForm = {
        materialCode: "",
        materialName: "",
        remark1: "",
        remark2: "",
      };
      this.materialSearchText = "";
      this.showMaterialDropdown = false;

      uni.showToast({
        title: "表单已重置",
        icon: "success",
      });
    },
  },
  beforeDestroy() {
    // 移除点击外部事件监听
    this.removeClickOutsideListener();

    // 停止PDA扫码，释放资源（来自mixin）
    this.stopPdaScan();
  },
};
</script>

<style scoped lang="scss">
@import "~@/pages/smart/scss/create.scss";

/* 物料明细码开关样式 */
.input-switch-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: auto;
}

.switch-label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  text-align: right;
  margin-right: 8px;
}

.custom-switch-wrapper {
  cursor: pointer;
}

.custom-switch {
  position: relative;
  width: 44px;
  height: 24px;
  background-color: #ccc;
  border-radius: 12px;
  transition: background-color 0.3s;
}

.custom-switch-active {
  background-color: #007aff;
}

.custom-switch-handle {
  position: absolute;
  top: 2px;
  left: 2px;
  width: 20px;
  height: 20px;
  background-color: #fff;
  border-radius: 50%;
  transition: transform 0.3s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.custom-switch-handle-active {
  transform: translateX(20px);
}

/* 表单样式调整 */
.form-item {
  position: relative;
  margin-bottom: 16px;
}

.material-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  background: #fff;

  &:disabled {
    background: #f5f5f5;
    color: #666;
  }
}

/* 物料组合选择器样式 */
.material-combo-selector {
  position: relative;
  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: #fff;

  &:focus-within {
    border-color: #007aff;
    box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.2);
  }
}

.material-input {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  background: transparent;
  outline: none;

  &:disabled {
    background: #f5f5f5;
    color: #666;
  }
}

.input-arrow {
  padding: 0 12px;
  color: #999;
  font-size: 12px;
  cursor: pointer;
  user-select: none;

  &:active {
    color: #666;
  }
}

/* 下拉选项样式 */
.material-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  max-height: 200px;
  overflow-y: auto;
  background: #fff;
  border: 1px solid #ddd;
  border-top: none;
  border-radius: 0 0 6px 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.material-option {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;

  &:last-child {
    border-bottom: none;
  }

  &:hover {
    background-color: #f8f9fa;
  }

  &:active {
    background-color: #e9ecef;
  }
}

.material-option-code {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.material-option-name {
  color: #666;
  font-size: 12px;
  margin-top: 2px;
}

.no-results {
  padding: 16px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.warehouse-display {
  padding: 12px;
  background: #f5f5f5;
  border-radius: 6px;
  font-size: 14px;
  color: #666;
}
</style>
